<template>
  <el-dialog
    title="菜品明细列表"
    :visible.sync="dialogValue"
    width="800px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="dish-list">
      <div class="list-header">
        <h4>比价项目：{{ biddingInfo?.title }}</h4>
        <p>共 {{ dishList.length }} 个菜品</p>
      </div>

      <el-table
        :data="dishList"
        stripe
        border
        size="small"
        max-height="500px"
        v-loading="loading"
      >
        <el-table-column prop="category" label="菜品分类" width="120"/>
        <el-table-column prop="name" label="菜品名称" min-width="150"/>
        <el-table-column prop="unit" label="单位" width="80"/>
        <el-table-column prop="base_price" label="官方参考价格" width="120">
          <template slot-scope="scope">
            <span style="color: #E6A23C; font-weight: bold;">¥{{ scope.row.base_price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="导入日期" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="success" @click="showAddDishDialog = true">增加菜品</el-button>
      <el-button type="primary" @click="exportDishList" :loading="exporting">导出Excel</el-button>
      <el-button @click="dialogValue = false">关闭</el-button>
    </div>


  <!-- 增加菜品对话框 -->
  <el-dialog
    title="增加菜品"
    :visible.sync="showAddDishDialog"
    width="600px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="add-dish-dialog">
      <el-alert
        title="增加菜品说明"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;"
      >
        <div slot="description">
          <p>在比价结束后，如果发现缺少菜品，可以在此处单独增加。</p>
          <!-- <p>新增的菜品将添加到官方参考价格表中，供应商需要重新报价。</p> -->
        </div>
      </el-alert>

      <el-form
        ref="addDishForm"
        :model="addDishForm"
        :rules="addDishRules"
        label-width="100px"
      >
        <el-form-item label="菜品分类" prop="category">
          <el-input
            v-model="addDishForm.category"
            placeholder="请输入菜品分类，如：蔬菜类、肉类等"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="菜品名称" prop="name">
          <el-input
            v-model="addDishForm.name"
            placeholder="请输入菜品名称"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item label="单位" prop="unit">
          <el-input
            v-model="addDishForm.unit"
            placeholder="请输入单位，如：斤、个、份等"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="官方参考价格" prop="base_price">
          <el-input-number
            v-model="addDishForm.base_price"
            :precision="2"
            :step="0.1"
            :min="0"
            placeholder="请输入官方参考价格"
            style="width: 100%;"
          />
        </el-form-item>
      </el-form>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="showAddDishDialog = false">取消</el-button>
      <el-button
        type="primary"
        @click="submitAddDish"
        :loading="submittingDish"
      >
        确认增加
      </el-button>
    </div>
  </el-dialog>
  </el-dialog>
</template>

<script>
import { http } from '@/api';
import * as XLSX from 'xlsx';

export default {
  name: 'DishList',
  data() {
    return {
      dialogValue: false,
      biddingInfo: null,
      dishList: [],
      loading: false,
      exporting: false,

      // 增加菜品相关
      showAddDishDialog: false,
      submittingDish: false,
      addDishForm: {
        category: '',
        name: '',
        unit: '',
        base_price: null
      },
      addDishRules: {
        category: [
          { required: true, message: '请输入菜品分类', trigger: 'blur' },
          { min: 1, max: 50, message: '菜品分类长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' },
          { min: 1, max: 100, message: '菜品名称长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' },
          { min: 1, max: 20, message: '单位长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        base_price: [
          { required: true, message: '请输入官方参考价格', trigger: 'blur' },
          { type: 'number', min: 0, message: '官方参考价格必须大于等于0', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    open(biddingInfo) {
      this.dialogValue = true;
      this.biddingInfo = biddingInfo;
      this.loadDishList();
    },

    loadDishList() {
      if (!this.biddingInfo) return;

      this.loading = true;
      // 调用获取菜品列表的接口
      http.dish.list({ monthly_bidding_id: this.biddingInfo.id }).then(res => {
        this.dishList = res.data || [];
        this.loading = false;
      }).catch((error) => {
        console.error('获取菜品列表失败:', error);
        this.loading = false;
        this.$message.error('获取菜品列表失败');
        this.dishList = [];
      });
    },

    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    exportDishList() {
      if (!this.dishList || this.dishList.length === 0) {
        this.$message.warning('没有数据可以导出');
        return;
      }

      this.exporting = true;

      try {
        // 准备导出数据，价格设置为空
        const exportData = this.dishList.map(item => ({
          '菜品分类': item.category || '',
          '菜品名称': item.name || '',
          '单位': item.unit || '',
          '报价': '', // 价格设置为空
        }));

        // 创建工作簿
        const workbook = XLSX.utils.book_new();

        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(exportData);

        // 设置列宽
        const colWidths = [
          { wch: 15 }, // 菜品分类
          { wch: 20 }, // 菜品名称
          { wch: 10 }, // 单位
          { wch: 12 }, // 菜品价格
        ];
        worksheet['!cols'] = colWidths;

        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet, '菜品明细');

        // 生成Excel文件
        const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });

        // 生成文件名
        const fileName = `${this.biddingInfo?.title || '菜品明细'}_供应商报价模版_${new Date().toISOString().slice(0, 10)}.xlsx`;

        // 创建blob并下载
        const blob = new Blob([excelBuffer], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success('导出成功');

      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败: ' + error.message);
      } finally {
        this.exporting = false;
      }
    },

    // 增加菜品相关方法
    submitAddDish() {
      this.$refs.addDishForm.validate(async (valid) => {
        if (!valid) {
          this.$message.warning('请完善菜品信息');
          return;
        }

        // 检查菜品是否已存在
        const existingDish = this.dishList.find(dish =>
          dish.name === this.addDishForm.name &&
          dish.category === this.addDishForm.category &&
          dish.unit === this.addDishForm.unit
        );

        if (existingDish) {
          this.$message.error('该菜品已存在于官方参考价格表中');
          return;
        }

        this.submittingDish = true;
        try {
          const dishData = {
            monthly_bidding_id: this.biddingInfo.id,
            category: this.addDishForm.category,
            name: this.addDishForm.name,
            unit: this.addDishForm.unit,
            base_price: this.addDishForm.base_price
          };

          const res = await http.dish.create(null,dishData);

          this.$message.success('菜品增加成功');
          this.showAddDishDialog = false;

          // 重置表单
          this.resetAddDishForm();

          // 重新加载数据
          await this.loadDishList();

          // 通知父组件更新
          this.$emit('dish-added', this.biddingInfo);

        } catch (error) {
          console.error('增加菜品失败:', error);
          this.$message.error('增加菜品失败');
        } finally {
          this.submittingDish = false;
        }
      });
    },

    resetAddDishForm() {
      this.addDishForm = {
        category: '',
        name: '',
        unit: '',
        base_price: null
      };
      this.$nextTick(() => {
        this.$refs.addDishForm && this.$refs.addDishForm.clearValidate();
      });
    }
  }
};
</script>

<style scoped lang="scss">
.dish-list {
  .list-header {
    margin-bottom: 20px;

    h4 {
      margin: 0 0 10px 0;
      color: #303133;
    }

    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }
}

.dialog-footer {
  text-align: right;
}

.add-dish-dialog {
  .el-form-item {
    margin-bottom: 20px;
  }

  .el-input-number {
    width: 100%;
  }
}
</style>
